package sunwul.mall.auth.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sunwul.mall.auth.strategy.LoginStrategy;
import sunwul.mall.auth.strategy.factory.LoginStrategyFactory;
import sunwul.mall.commonbase.constant.AuthConstants;

import javax.servlet.http.HttpServletRequest;

/**
 * @author sunwul
 * @date 2024/12/26 10:28
 * @description SpringSecurity  UserDetailsService自定义实现
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private LoginStrategyFactory loginStrategyFactory;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获取请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            throw new RuntimeException("请求对象获取失败!");
        }

        // 从请求头获取登录类型
        HttpServletRequest request = requestAttributes.getRequest();
        String loginType = request.getHeader(AuthConstants.LOGIN_TYPE);
        if (!StringUtils.hasText(loginType)) {
            throw new InternalAuthenticationServiceException("非法登录, 登录类型不匹配!");
        }
        // 通过策略工厂根据登录类型获取具体的登录策略
        LoginStrategy instance = loginStrategyFactory.getInstance(loginType);
        return instance.realLogin(username);
    }
}
